#!/usr/bin/env ruby
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Use of this source code is governed by a BSD-type license.
# See the COPYING file for details.

# Creates the <link> tests (placing them in link/) from the <style> tests (taken
# from style/).
#
# This script must be run before running the test harness, otherwise you'll see
# a whole bunch of orange-bordered iframes in the test results.
#
# Author: Benjamin Kalman <kalman@chromium.org>

$style_dir = 'style'
$link_dir = 'link'

if not File.directory?($style_dir)
  testsDir = 'tests'
  $style_dir = testsDir + '/' + $style_dir
  $link_dir = testsDir + '/' + $link_dir
  if not File.directory?($style_dir)
    puts('Cannot find tests; make sure this script is being run from either excss/ or tests/')
    exit 1
  end
end

def makeLinkTest(name)
  warning = "DO NOT EDIT: this file was automatically generated by #{$0}."

  htmlFile = File.new($link_dir + '/' + name + '.html', 'w')
  htmlFile.puts("<!-- #{warning} -->")

  File.open($style_dir + '/' + name + '.html', 'r') do |file|
    inStyle = false
    exCssFile = nil;
    exCssFileCount = 0;

    file.each_line do |line|
      if line =~ /<style/
        inStyle = true
        exCssFilename = name + exCssFileCount.to_s + '.excss';
        exCssFileCount += 1;
        htmlFile.puts('<head>')
        htmlFile.puts('  <link rel="stylesheet" href="' + exCssFilename + '"' + line['<style'.length..-1])
        htmlFile.puts('</head>')
        exCssFile = File.new($link_dir + '/' + exCssFilename, 'w')
        exCssFile.puts("/* #{warning} */")
      elsif line =~ /<\/style/
        inStyle = false
        htmlFile.puts('<body>')
        exCssFile.close();
      elsif inStyle
        exCssFile.puts(line.sub(/^  /, ''))
      else
        htmlFile.puts('  ' + line)
      end
    end
  end

  htmlFile.puts('</body>')
  htmlFile.close()
end

if File.directory?($link_dir)
  Dir.entries($link_dir).each do |entry|
    filename = $link_dir + '/' + entry
    if File.file?(filename)
      File.delete(filename)
    end
  end
else
  Dir.mkdir($link_dir)
end

# We should not produce link variants of the tests of the parser extension
# mechanism, as the extensions won't work in the server backend preprocessor
# and the tests will fail. List such tests here.
$exclusions = ['parserExtension.html', 'parserExtension2.html']

Dir.entries($style_dir).each do |entry|
  stripped_entry = entry.sub(/#{$style_dir}\//, '')
  if entry =~ /\.html$/ and $exclusions.index(stripped_entry).nil?
    puts('Processing style/' + entry + '...')
    makeLinkTest(entry.sub(/\.html$/, ''))
  end
end
